import React, { ReactNode, useEffect, useState } from 'react'
import { FormModal } from '@/app/component/form-modal';
import '@/app/component/form.css'
import classNames from 'classnames';
import { ChevronDown, X } from 'lucide-react';
import { MySelect, SelectOption } from '@/app/component/my-select';
import { findIndex, set } from 'lodash';
import MyInput from '../my-input';
import MySlider from '../my-slider';


import Slider from 'rc-slider';
import 'rc-slider/assets/index.css';
import '@/app/component/my-slider/style.css';

interface MyRangerProps {
  value?: (number | undefined)[]
  onChange?: (value: (number | undefined)[]) => void
  placeholder?: string // 占位符
  className?: string // 自定义类名
  prefix?: ReactNode // 前缀
  suffix?: ReactNode // 后缀
  disabled?: boolean // 禁用
  name?: string // 组件名
  max: number // 最大值
  min: number // 最小值
  step?: number // 步长
}

const MyRanger = <T, IsNumber extends boolean = false>({
  value,
  onChange,
  placeholder,
  className,
  prefix,
  suffix,
  disabled, 
  name = '',
  max,
  min,
  step=1,
}: MyRangerProps) => {
  const [open, setOpen] = useState(false)
  // 临时存储的value
  // const [tempValue1, setTempValue1] = useState<number | undefined>(value?.[0])
  // const [tempValue2, setTempValue2] = useState<number | undefined>(value?.[1])
  const [tempValue, setTempValue] = useState<{
    value1: number | undefined,
    value2: number | undefined,
  }>({
    value1: value?.[0],
    value2: value?.[1]
  })
  // slider值控制器
  const [sliderValue, setSliderValue] = useState<[number, number]>([tempValue.value1 ?? min, tempValue.value2 ?? max + step]);

  // 判断是不是有效值
  const isValueValid = (value: (number | undefined)[]) => {
    // value只要有一个非undefined就返回true
    return value?.some((item) => item !== undefined)
  }

  // 外部点击清除所有
  const handleClearAll = () => {
    onChange?.([undefined, undefined])
    setTempValue({
      value1: undefined,
      value2: undefined,
    })
    setOpen(false)
    setSliderValue([min, max + step])
  }

  // trigger ---------------------------------------------------
  const defaultTrigger = (
    <div onClick={()=>{setOpen(true)}} className={classNames('ranger-layout group', {
        'ranger-layout--placeholder': !isValueValid(value || []),
        'ranger-layout--focus': open,
        'ranger-layout--disabled': disabled
      }, className)}>
      {/* 前缀 */}
      {prefix}
      {/* 文本 */}
      <div className={classNames('ranger-text')}>
        {isValueValid(value || []) 
          ? (value?.[0] !== undefined ? value[0] : 'Any') + ' - ' + (value?.[1] !== undefined ? value[1] : 'Any') 
          : placeholder
        }
      </div>
      {/* 指示器 */}
      <div className='ranger-indicator'>
        <div className='ranger-indicator-container'>
          <ChevronDown className={classNames('ranger-indicator-arrow', {
            'rotate-180': open,
          })} />
        </div>
        <div className='ranger-indicator-container'>
          <X className={classNames('ranger-indicator-close opacity-0 group-hover:opacity-100 transition-all duration-100', {
            'hidden': !isValueValid(value || [])
          })}
            onClick={(e) => {
              e?.stopPropagation();
              handleClearAll();
            }}
          />
        </div>
      </div>
      {/* 后缀 */}
      {suffix}
    </div>
  )

  // content ---------------------------------------------------
  const content = (
    <div>
      <div className='flex gap-2 items-center justify-between'>
        <span className='flex-1 min-w-0 gap-2 shrink-0 font-semibold'>Min {name}</span>
        <span className='opacity-0'>-</span>
        <span className='flex-1 min-w-0 gap-2 shrink-0 font-semibold'>Max {name}</span>
      </div>
      {/* <div className='flex gap-2 items-center'>
        <MySelect<number, false> name={'Start ' + name} prefix={<span className='opacity-50'>From</span>} className='flex-1' value={tempValue1} onChange={(value) => {
          setTempValue1(value)
        }} options={options1} />
        <span>-</span>
        <MySelect<number, false> name={'End ' + name} prefix={<span className='opacity-50'>To</span>} className='flex-1' value={tempValue2} onChange={(value) => {
          setTempValue2(value)
        }} options={options2} />
      </div> */}
      <div className='flex gap-2 items-center mt-1'>
        <MyInput 
          placeholder={String(min)} 
          precision={0} 
          className='flex-1' 
          number 
          min={min}
          max={max}
          value={tempValue.value1} 
          onChange={(value)=>handleMinInputChange(value)} 
          onBlur={()=>handleInputBlur()}
          onClear={()=>handleMinInputClear()}
          prefix={<span className='opacity-50'>From</span>} 
        />
        <span>-</span>
        <MyInput 
          placeholder='Any' 
          precision={0} 
          className='flex-1' 
          number 
          min={min}
          max={max}
          value={tempValue.value2}
          onChange={(value) => handleMaxInputChange(value)}
          onBlur={()=>handleInputBlur()}
          onClear={()=>handleMaxInputClear()}
          prefix={<span className='opacity-50'>To</span>} 
        />
      </div>

      <div className={'mt-4 px-2'}>
        {/* 刻度尺 */}
        <ul className='flex items-left justify-between mb-[-6px]'>
          {new Array(((max-min+step)/step + 1)).fill(0).map((_, index) => (<li key={index} className={classNames('text-[10px] w-[1px] flex flex-col items-left justify-center', {
            'opacity-0': index % 3 !== 0,
            'opacity-100': index === 0 || index === ((max-min+step)/step + 1) - 1,
            'items-end': index === ((max-min+step)/step + 1) - 1,
          })}>
            <span className='w-full flex justify-center items-center'>{index === ((max-min+step)/step + 1) - 1? 'Any' : index * step}</span>
            <div className='w-[1px] h-[8px] bg-black/10' />
          </li>))}
        </ul>
        <Slider step={step} value={sliderValue} onChange={(newVal)=>{handleSliderChange(newVal as [number, number])}} min={min} max={max + step} range />
      </div>
    </div>
  )

  // confirm按钮处理 ----------------------------------------------
  const handleConfirm = () => {
    // 转换为数字并验证有效性
    const num1 = Number(tempValue.value1);
    const num2 = Number(tempValue.value2);
    let val1 = tempValue.value1;
    let val2 = tempValue.value2;

    // 处理单个值或两个值的情况 - 最小值判断
    const minNum = Number(min);
    if (!isNaN(minNum)) {
      // 处理第一个值的最小值
      if (!isNaN(num1) && num1 < minNum) {
        val1 = min;
      }
      // 处理第二个值的最小值
      if (!isNaN(num2) && num2 < minNum) {
        val2 = min;
      }
    }

    // 处理单个值或两个值的情况 - 最大值判断
    const maxNum = Number(max);
    if (!isNaN(maxNum)) {
      // 处理第一个值的最大值
      if (!isNaN(num1) && num1 > maxNum) {
        val1 = max;
      }
      // 处理第二个值的最大值
      if (!isNaN(num2) && num2 > maxNum) {
        val2 = max;
      }
    }

    // 当两个值都存在时，确保顺序正确
    if (!isNaN(num1) && !isNaN(num2)) {
      // 重新获取处理后的值进行比较（因为可能被min/max调整过）
      const processedNum1 = Number(val1);
      const processedNum2 = Number(val2);
      
      if (processedNum1 > processedNum2) {
        [val1, val2] = [val2, val1];
      }
    }

    // 更新状态并回调
    setTempValue({
      value1: val1,
      value2: val2,
    })
    console.log([val1, val2]);
    
    onChange?.([val1, val2]);
    setOpen(false);
  }

  // 输入方法的处理 ---------------------------------------------------
  // 滑块组件处理
  const handleSliderChange = (newVal: [number, number])=>{
    let val = newVal
    setSliderValue(val)
    setTempValue({
      value1: val[0] === min ? undefined : val[0],
      value2: val[1] === max + step ? undefined : val[1],
    })
  }
  // input组件处理
  const handleMinInputChange = (value: number | undefined) => {
    setTempValue({
      ...tempValue,
      value1: value
    })
  }
  const handleMaxInputChange = (value: number | undefined) => {
    setTempValue({
      ...tempValue,
      value2: value
    })
  }
  const handleInputBlur = () => {
    // 1. 先计算处理后的值（避免重复逻辑）
    const newValue1 = tempValue.value1 && (tempValue.value1 < min || tempValue.value1 > max) 
      ? undefined 
      : tempValue.value1;
    
    const newValue2 = tempValue.value2 && (tempValue.value2 < min || tempValue.value2 > max) 
      ? undefined 
      : tempValue.value2;

    // 2. 更新 tempValue（函数式更新确保基于最新状态）
    setTempValue(prev => ({
      value1: newValue1,
      value2: newValue2
    }));

    // 3. 直接使用计算好的 newValue 更新 slider（而非依赖 tempValue）
    setSliderValue([
      newValue1 ?? min,
      newValue2 ?? (max + step)
    ]);
  };
  const handleMinInputClear = ()=>{
    setTempValue({
      ...tempValue,
      value1: undefined
    })
    setSliderValue([min, sliderValue[1]])
  }
  const handleMaxInputClear = ()=>{
    setTempValue({
      ...tempValue,
      value2: undefined
    })
    setSliderValue([sliderValue[0], max + step])
  }
  
  
  return (
    <div>
      <FormModal open={open} onOpenChange={setOpen} 
        trigger={defaultTrigger}
        header={name}
        content={<div>
          {content}
        </div>}
        footer={<div className='flex gap-2'>
          <button className='flex-1 border border-black rounded-sm px-2 py-1 bg-transparent text-black' onClick={()=>{
            setTempValue({
              value1: undefined,
              value2: undefined,
            })
          }}>Clear All</button>
          <button 
            className='flex-1 border border-black rounded-sm px-2 py-1 bg-black text-white' 
            onClick={handleConfirm}
          >
            Confirm
          </button>
        </div>}
      />
    </div>
  )
}

export default MyRanger